package com.wjb.xietong.control;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;

import com.wjb.xietong.R;
import com.wjb.xietong.W3.BitmapLruImageCache;
import com.wjb.xietong.component.AppGlobal;
import com.wjb.xietong.ota.task.PhotoDetailView;
import com.wjb.xietong.util.LogD;

public class AsyncImageLoader {
	private volatile static AsyncImageLoader instance;
	// 最大缓存大小
	private static int IMAGE_CACHE_MAX_SIZE = 1024 * 1024 * 10;
	private BitmapLruImageCache mImageCache = new BitmapLruImageCache(IMAGE_CACHE_MAX_SIZE);
 
    private AsyncImageLoader() {
    }
    
    public static AsyncImageLoader Instance() {
		if (instance == null) {
			synchronized (AsyncImageLoader.class) {
				if (instance == null) {
					instance = new AsyncImageLoader();
				}
			}
		}
		return instance;
	}
    
    public void loadForImageView(final String imageUrl, final ImageView imageView, final int defResource){
    	if (null != mImageCache.getBitmap(imageUrl)) {
    		imageView.setImageBitmap(mImageCache.getBitmap(imageUrl));
        }else{
        	imageView.setImageResource(defResource);
        	final Handler handler = new Handler(Looper.getMainLooper()) {
        		@Override
        		public void handleMessage(Message message) {
        			final Bitmap bitmap = (Bitmap) message.obj;
        			imageView.setImageBitmap(bitmap);
        		}
        	};
        	new Thread(new Runnable() {
				
				@Override
				public void run() {
					Bitmap bitmap = loadImageFromUrl(imageUrl);
					if(bitmap != null){
	        			mImageCache.putBitmap(imageUrl, bitmap);
	        			Message message = handler.obtainMessage(0, bitmap);
	        			handler.sendMessage(message);
					}
				}
			}).start();
        }
    }
    /**
     * set net image for ImageView
     * @param imageUrl image's url
     * @param imageView ImageView Object
     * @param defResource default image resource
     */
    public void loadDrawableForImageView(final String imageUrl, final ImageView imageView, final int defResource){
    	if (null != mImageCache.getBitmap(imageUrl)) {
        	imageView.setImageBitmap(mImageCache.getBitmap(imageUrl));
        	imageView.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
					showImagePopupWindow(imageView, mImageCache.getBitmap(imageUrl));
				}
			});
        }else{
        	imageView.setImageResource(defResource);
//        	imageView.setOnClickListener(new OnClickListener() {
//				
//				@Override
//				public void onClick(View arg0) {
//					 Activity act = AppGlobal.getInstance().getActManager().currentActivity();
//					showImagePopupWindow(imageView, new BitmapDrawable(BitmapFactory.decodeResource(act.getResources(), defResource)));
//				}
//			});
        	final Handler handler = new Handler(Looper.getMainLooper()) {
        		@Override
        		public void handleMessage(Message message) {
        			final Bitmap bitmap = (Bitmap) message.obj;
        			imageView.setImageBitmap(bitmap);
        			imageView.setOnClickListener(new OnClickListener() {
						
						@Override
						public void onClick(View arg0) {
							showImagePopupWindow(imageView, bitmap);
						}
					});
        		}
        	};
        	new Thread(new Runnable() {
				
				@Override
				public void run() {
					Bitmap bitmap = loadImageFromUrl(imageUrl);
					if(bitmap != null){
	        			mImageCache.putBitmap(imageUrl, bitmap);
	        			Message message = handler.obtainMessage(0, bitmap);
	        			handler.sendMessage(message);
					}
				}
			}).start();
        }
    }
    
    private void showImagePopupWindow(View v, Bitmap bitmap){
        Activity act = AppGlobal.getInstance().getActManager().currentActivity();
    	final PopupWindow popupW = new PopupWindow(act) ;  
        popupW.setWidth(AppGlobal.getInstance().getScreenWidth()) ;  
        popupW.setHeight(AppGlobal.getInstance().getScreenHeight()) ;  
//        popupW.setAnimationStyle(R.style.AnimationFade) ;  
        popupW.setBackgroundDrawable(act.getResources().getDrawable(R.drawable.trans)) ;  
        popupW.setContentView(act.getLayoutInflater().inflate(R.layout.popup_image_detial,null)) ;  
        
        PhotoDetailView imageDetail = (PhotoDetailView)popupW.getContentView().findViewById(R.id.id_photodetail);
        imageDetail.setImageBitmap(bitmap);
        
        Button btnClose = (Button)popupW.getContentView().findViewById(R.id.id_close);
        btnClose.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				popupW.dismiss();
			}
		});
        
        popupW.setFocusable(true);
        
        popupW.showAtLocation(v, Gravity.CENTER, 0, 0);
    }
    
	private Bitmap loadImageFromUrl(String imageUrl) {
		URL url = null;
		InputStream inputStream = null;
		try {
			url = new URL(changeUrl(imageUrl));
			inputStream = (InputStream) url.getContent();
			BitmapFactory.Options opts=new BitmapFactory.Options();
			opts.inPreferredConfig = Bitmap.Config.RGB_565;
			return BitmapFactory.decodeStream(inputStream, null, opts);  
		} catch (Exception e) {
			LogD.output("[AsyncImageLoader] : [loadImage] → " + e.getMessage());
		} finally {
			try {
				if (inputStream != null)
					inputStream.close();
			} catch (IOException e) {
				LogD.output("[AsyncImageLoader] : [loadImage] → " + e.getMessage());
			}
		}
		return null;
	}
	
	private String changeUrl(String imageUrl){
		if(-1 == imageUrl.indexOf("?")){
			return imageUrl;
		}
		imageUrl = imageUrl.substring(0, imageUrl.indexOf("?"));
		if(imageUrl.contains("wjbwork")){
			imageUrl = "http://workfile.wangjubao.com" + imageUrl.substring(imageUrl.lastIndexOf("/"), imageUrl.length());
		}
		imageUrl = imageUrl + "@500w_90Q_1x.png";
		return imageUrl;
	}
 
	/**
	 * clear all the image cache
	 */
	public void clearImageCache(){
//		imageCache.clear();
	}
}

